package com.sduept.nwld.dataserver.rest;

import com.sduept.core.dao.SuperDAO;
import com.sduept.generator.ObjectId;
import com.sduept.nwld.dataserver.manager.countanalyse.ProtectKpiAnalysisManger;
import com.sduept.nwld.dataserver.manager.statistics.FaultTimeAnalysisCountManager;
import com.sduept.nwld.dataserver.manager.statistics.FaultTimeAnalysisManager;
import com.sduept.nwld.dataserver.manager.statistics.FaultTimeAnalysisManager.FaultContinuedTimeCountstrategy;
import com.sduept.nwld.dataserver.manager.statistics.ProtectKpiManager;
import com.sduept.nwld.dataserver.manager.statistics.StatisticsCommonManager;
import com.sduept.nwld.dataserver.model.countanalyse.FaultFastRemove;
import com.sduept.nwld.dataserver.model.faulttimeanalysis.BreakerActTimeCount;
import com.sduept.nwld.dataserver.model.faulttimeanalysis.FaultContinuedTimeCount;
import com.sduept.nwld.dataserver.model.faulttimeanalysis.ProtectActTimeCount;
import com.sduept.utils.DateUtil;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 系统故障时间分析（保护动作时间、故障持续时间）
 * @author Administrator
 *
 */
@RestController
@RequestMapping("/fault/")
public class FaultTimeAnalysisServices {

	@Autowired
	private SuperDAO dao;
	@Autowired
	private FaultTimeAnalysisManager manager;
	@Autowired
	private StatisticsCommonManager comM;
	@Autowired
	private FaultTimeAnalysisCountManager countM;
	@Autowired
	private ProtectKpiAnalysisManger analysisM;
	@Autowired
	private ProtectKpiManager kpiM;
	private DecimalFormat df = new DecimalFormat("#0.00");

//***************************************故障持续时间******************************
	/**
	 * 根据年、电压等级，获取故障持续时间的统计数据
	 * @param startYear
	 * @param endYear
	 * @param voltage
	 * @return
	 */

	@GetMapping("/getFaultContinuedTimeCount/{startYear}/{endYear}/{voltage}")
	public String getFaultContinuedTimeCountByStartYearAndEndYear(@PathVariable("startYear") String startYear,@PathVariable("endYear") String endYear,@PathVariable("voltage") String voltage) {
		List<FaultContinuedTimeCount> list = new ArrayList<FaultContinuedTimeCount>();
		Integer start = Integer.parseInt(startYear);
		Integer end = Integer.parseInt(endYear);
		Integer v = Integer.parseInt(voltage);
		List<Integer> voltages = new ArrayList<Integer>();
		if (v != 0) {
			voltages.add(v);
		} else if (v == 0) {
			voltages = comM.getVoltages();
		}
		if (start.equals(end)) {// 需要的是平均时间
			// 查询当年度1-12月份的数据
			// list = getMonthListByYearAndVol(start, voltages);
			list = getFaultContinuedTimeByMonthAndVolfromOMS(start, voltages);
		} else {
			// 查询从startYear到endYear的年度数据
			for (int y = start; y <= end; y++) {
				// list.addAll(getYearListByYearAndVol(y, voltages));
				list.addAll(getFaultContinuedTimeByYearAndVolOMS(y, voltages));
			}
		}
		JSONArray jsa = new JSONArray();
		for (FaultContinuedTimeCount count : list) {
			JSONArray jsArr = new JSONArray();
			jsArr.add(count.getYear());
			jsArr.add(count.getMonth());
			jsArr.add(count.getVoltage());
			jsArr.add(df.format(count.getFaultTimeAve()));
			jsa.add(jsArr);
		}
		return jsa.toString();
	}

	/**
	 * 根据年、电压等级，获取年度数据
	 * @param year
	 * @param voltage
	 * @return
	 */
	private List<FaultContinuedTimeCount> getYearListByYearAndVol(Integer year, List<Integer> voltages) {
		List<FaultContinuedTimeCount> result = new ArrayList<FaultContinuedTimeCount>();
		for (Integer vol : voltages) {
			// 首先查询全年的数据
			List<FaultContinuedTimeCount> list = manager.findYearFaultContinuedTimeCount(year, vol, null);
			if (list.size() == 0) {
				// 全年数据不存在时，查询当年1-12月份的数据
				list = manager.findMonthFaultContinuedTimeCount(year, null, vol, null);
			}
			Float avg = getSumAvgFaultTime(list);
			FaultContinuedTimeCount count = new FaultContinuedTimeCount();
			count.setFaultTimeAve(Float.valueOf(df.format(avg)));
			count.setYear(year);
			count.setVoltage(vol);
			result.add(count);
		}
		return result;
	}

	private Float getSumAvgFaultTime(List<FaultContinuedTimeCount> list) {
		Float result = 0f;
		if (list.size() > 0) {
			Float sum = 0f;
			for (FaultContinuedTimeCount count : list) {
				if(null!=count.getFaultTimeAve()) {
					sum += count.getFaultTimeAve();
				}
			}
			result = sum / list.size();
		}
		return result;
	}

	/**
	 * 根据年、电压等级，获取当年1-12月份的数据
	 * @param year
	 * @param v
	 * @return
	 */
	private List<FaultContinuedTimeCount> getMonthListByYearAndVol(Integer year, List<Integer> voltages) {
		List<FaultContinuedTimeCount> list = new ArrayList<FaultContinuedTimeCount>();
		for (Integer vol : voltages) {
			List<FaultContinuedTimeCount> results = manager.findMonthFaultContinuedTimeCount(year, null, vol, null);
			list.addAll(countListByMonth(results, year, vol));
		}
		return list;
	}

	/**
	 * 根据年、电压等级，获取年度数据
	 * @param year
	 * @param voltage
	 * @return
	 */
	private List<FaultContinuedTimeCount> getFaultContinuedTimeByYearAndVolOMS(Integer year, List<Integer> voltages) {
		FaultContinuedTimeCountstrategy oms = manager.new OMSCountstrategy();
		List<FaultContinuedTimeCount> list = new ArrayList<FaultContinuedTimeCount>();
		List<FaultContinuedTimeCount> result = new ArrayList<FaultContinuedTimeCount>();
		for (Integer vol : voltages) {
			list = getFaultContinuedTimeCount(oms.findActTimeCount(year, null, vol, null));
			Float avg = getSumAvgFaultTime(list);
			FaultContinuedTimeCount count = new FaultContinuedTimeCount();
			count.setFaultTimeAve(Float.valueOf(df.format(avg)));
			count.setYear(year);
			count.setVoltage(vol);
			result.add(count);
		}
		return result;
	}

	/**
	 * 根据年、电压等级，获取当年1-12月份的数据  对时间进行求平均处理
	 * @param year
	 * @param v
	 * @return
	 */
	public List<FaultContinuedTimeCount> getFaultContinuedTimeByMonthAndVolfromOMS(Integer year, List<Integer> voltages) {
		FaultContinuedTimeCountstrategy oms = manager.new OMSCountstrategy();
		List<FaultContinuedTimeCount> list = new ArrayList<FaultContinuedTimeCount>();
		for (Integer vol : voltages) {
			List<FaultContinuedTimeCount> results = getFaultContinuedTimeCount(oms.findActTimeCount(year, null, vol, null));
			list.addAll(countListByMonth(results, year, vol));
		}

		return list;
	}

	/**
	 * 根据查询出的集合组合成map 根据相同的日期+电压等级 获取平均时间  
	 * @param list2
	 * @return  List<FaultContinuedTimeCount>
	 */
	private List<FaultContinuedTimeCount> getFaultContinuedTimeCount(List<?> list2) {
		List<FaultContinuedTimeCount> list = new ArrayList<FaultContinuedTimeCount>();
		Map<String, List<Object>> map = getMap(list2);
		for (String key : map.keySet()) {
			List<Object> lt = map.get(key);
			if (null != lt) {
				double totalTime = 0;
				int num = 0;
				for (Object obj : lt) {
					Object[] objs = (Object[]) obj;
					if (null != objs[11]) {// faultTime
						double faultTime = (Double.valueOf(objs[11].toString()));
						totalTime += faultTime;
						num++;
					}
				}
				FaultContinuedTimeCount record = new FaultContinuedTimeCount();
				record.setId(ObjectId.get().toString());
				String[] d = ((String) key).split("-");
				record.setYear(Integer.parseInt(d[0]));
				record.setMonth(Integer.parseInt(d[1]));
				int voltage = (Integer.valueOf(d[3].toString().replace(".0", "")));
				record.setVoltage(voltage);
				record.setStatus(0);
				// record.setSubCompany("-");
				if (num != 0) {
					String faultTimeAve = df.format((float) totalTime / (num));
					record.setFaultTimeAve(Float.parseFloat(faultTimeAve));
				}
				list.add(record);
			}
		}
		return list;
	}

	/**
	 * 根据数据集合获取map
	 * @param list2
	 * @return Map<String, List<Object>>   key:日期+电压等级  value:对应的数据
	 */
	private Map<String, List<Object>> getMap(List<?> list2) {
		Map<String, List<Object>> map = new HashMap<String, List<Object>>();
		for (Object object : list2) {
			Object[] objs = (Object[]) object;
			String date = objs[1].toString();
			String vol = objs[3].toString();
			if (StringUtils.isNotEmpty(date) && StringUtils.isNotEmpty(vol)) {
				String key = date + "-" + vol;// 2018-01-01-500
				List<Object> lt = map.get(key);
				if (null == lt) {
					lt = new ArrayList<Object>();
					map.put(key, lt);
				}
				lt.add(object);
			}
		}
		return map;
	}

	/**
	 * 根据年、月、电压等级，计算故障时间之和
	 * @param list
	 * @param year
	 * @param voltage
	 * @return
	 */
	private List<FaultContinuedTimeCount> countListByMonth(List<FaultContinuedTimeCount> list, Integer year, Integer voltage) {
		Map<Integer, List<FaultContinuedTimeCount>> map = new HashMap<>();
		for (FaultContinuedTimeCount count : list) {
			Integer m = count.getMonth();
			List<FaultContinuedTimeCount> lt = map.get(m);
			if (null == lt) {
				lt = new ArrayList<FaultContinuedTimeCount>();
				map.put(m, lt);
			}
			lt.add(count);
		}
		List<FaultContinuedTimeCount> results = new ArrayList<FaultContinuedTimeCount>();
		for (Integer m : map.keySet()) {
			List<FaultContinuedTimeCount> lt = map.get(m);
			Float sum = 0f;
			for (FaultContinuedTimeCount bean : lt) {
				if(bean.getFaultTimeAve()!=null) {
				 sum += bean.getFaultTimeAve();
				}
			}
			Float avg = 0f;
			if (lt.size() > 0) {
				avg = sum / lt.size();
			}
			FaultContinuedTimeCount result = new FaultContinuedTimeCount();
			result.setYear(year);
			result.setMonth(m);
			result.setVoltage(voltage);
			result.setFaultTimeAve(avg);
			results.add(result);
		}
		return results;
	}

	/**
	 * 根据年、电压等级，获取故障持续时间
	 * @param startYear
	 * @param endYear
	 * @param voltage
	 * @return
	 */

	@GetMapping("/getFaultContinuedTimeDetail/{startYear}/{endYear}/{voltage}")
	public String getFaultContinuedTimeDetail(@PathVariable("startYear") String startYear,@PathVariable("endYear") String endYear,@PathVariable("voltage") String voltage) {
		List<Object> result = new ArrayList<Object>();
		Integer start = Integer.parseInt(startYear);
		Integer end = Integer.parseInt(endYear);
		Integer v = Integer.parseInt(voltage);
		List<Integer> voltages = new ArrayList<Integer>();
		if (v != 0) {
			voltages.add(v);
		} else if (v == 0) {
			voltages = comM.getVoltages();
		}
		for (int year = start; year <= end; year++) {
			for (Integer vol : voltages) {
				List<?> list = countM.getFaultTimeDetail(year, null, vol);
				result.addAll(list);
			}
		}
		JSONArray jsa = new JSONArray();
		for (Object object : result) {
			Object[] obj = (Object[]) object;
			if (null != obj[3]) {
				JSONArray jsArr = new JSONArray();
				jsArr.add(obj[0]); // 年
				jsArr.add(obj[1]); // 月
				jsArr.add(obj[2]); // 电压
				String firstFault = obj[3].toString(); // 故障持续时间，微秒，需要转化为毫秒
				if (StringUtils.isNotEmpty(firstFault)) {
					float timeUs = Float.parseFloat(firstFault);
					jsArr.add(timeUs / 1000); // 故障持续时间，毫秒
				}
				jsa.add(jsArr);
			}
		}
		return jsa.toString();
	}

	/**
	 * 根据年、电压等级，获取故障持续时间
	 * 
	 * @param startYear
	 * @param endYear
	 * @param voltage
	 * @return
	 */

	@GetMapping("/getFaultContinuedTimeDetailfromOMS/{startYear}/{endYear}/{voltage}")
	public String getFaultContinuedTimeDetailfromOMS(@PathVariable("startYear") String startYear,@PathVariable("endYear") String endYear,@PathVariable("voltage") String voltage) {
		FaultContinuedTimeCountstrategy oms = manager.new OMSCountstrategy();
		List<Object> result = new ArrayList<Object>();
		Integer start = Integer.parseInt(startYear);
		Integer end = Integer.parseInt(endYear);
		Integer v = Integer.parseInt(voltage);
//		List<Integer> voltages = new ArrayList<Integer>();
//		if (v != 0) {
//			voltages.add(v);
//		} else if (v == 0) {
//			voltages = comM.getVoltages();
//		}
//		for (int year = start; year <= end; year++) {
//			for (Integer vol : voltages) {
//				List<?> list = oms.findActTimeCount(year, null, vol, null);
//				// List<?> list = countM.getFaultTimeDetail(year, null, vol);
//				result.addAll(list);
//			}
//		}
		for (int year = start; year <= end; year++) {
			List<?> list = oms.findActTimeCount(year, null, v, null);
			result.addAll(list);
	      }
		JSONArray jsa = new JSONArray();
		for (Object object : result) {
			Object[] obj = (Object[]) object;
			if (null != obj[11]) {// 故障持续时间
				Date faultTime = (Date) obj[1];
				String date = DateUtil.getStringDate(faultTime, DateUtil.pattern_ymd000);
				int year = Integer.valueOf(date.split("-")[0]);
				int month = Integer.valueOf(date.split("-")[1]);
				JSONArray jsArr = new JSONArray();
				jsArr.add(year); // 年
				jsArr.add(month); // 月
				jsArr.add(obj[3]); // 电压1
				String firstFault = obj[11].toString(); // 故障持续时间，微秒，需要转化为毫秒
				if (StringUtils.isNotEmpty(firstFault)) {
					float timeUs = Float.parseFloat(firstFault);
					jsArr.add(timeUs); // 故障持续时间，毫秒
				}
				jsa.add(jsArr);
			}
		}
		return jsa.toString();
	}

	/**
	 * 根据年、电压等级获取故障快速切除率
	 * @param startYear
	 * @param endYear
	 * @param voltage
	 * @return 
	 */

	@GetMapping("/getFaultFastRemove/{startYear}/{endYear}/{voltage}")
	public String getFaultFastRemove(@PathVariable("startYear") String startYear,@PathVariable("endYear") String endYear,@PathVariable("voltage") String voltage) {
		Integer start = Integer.parseInt(startYear);
		Integer end = Integer.parseInt(endYear);
		Integer vol = "0".equals(voltage) ? null : Integer.parseInt(voltage);

		List<FaultFastRemove> list = new ArrayList<FaultFastRemove>();
		for (int year = start; year <= end; year++) {
			List<FaultFastRemove> ffrs = analysisM.getSummaryOfFaultFastRemoveBySubCompany(year, null, vol);
			list.addAll(ffrs);
		}
		return getFaultFastRemoveRealityRatio(list);
	}


	@GetMapping("/getFaultFastRemoveFromOms/{startYear}/{endYear}/{voltage}")
	public String getFaultFastRemoveFromOms(@PathVariable("startYear") String startYear,@PathVariable("endYear") String endYear,@PathVariable("voltage") String voltage) {
		FaultContinuedTimeCountstrategy oms = manager.new OMSCountstrategy();
		Integer start = Integer.parseInt(startYear);
		Integer end = Integer.parseInt(endYear);
		Integer vol = "0".equals(voltage) ? null : Integer.parseInt(voltage);

		List<Object> list = new ArrayList<Object>();
		for (int year = start; year <= end; year++) {
			List<?> ffrs = oms.findActTimeCount(year, null, vol, null);
			list.addAll(ffrs);
		}
		return getFaultFastRemoveRealityRatioByOms(list);
	}
	private String getFaultFastRemoveRealityRatioByOms(List<Object> list) {
		float totalNum  = list.size();
		float actulProtectActNum = 0;//实际保护动作次数
		for (Object object : list) {
			Object[] obj = (Object[]) object;
			if(!"否".equals(obj[14])) {
				actulProtectActNum++;
			}
		}
		float 	FastRemoveRealityRatio =  actulProtectActNum/totalNum*100;
		String result = String.valueOf(FastRemoveRealityRatio);
		return result;
	}
	
	
	
	/**
	 * 获取实际完成率
	 * @param ffrs
	 * @return
	 */
	private String getFaultFastRemoveRealityRatio(List<FaultFastRemove> ffrs) {
		DecimalFormat df = new DecimalFormat("#.##");
		float actNumTotal = 0;
		float wantedTotal = 0;
		for (FaultFastRemove ffr : ffrs) {
			Integer actNum = ffr.getActNum();
			actNumTotal += actNum;
			Integer wanted = ffr.getWantedActNum();
			Float plan = ffr.getPlan();
			wantedTotal += wanted * plan / 100;
		}
		if (wantedTotal > 0) {
			float ratio = wantedTotal / actNumTotal * 100;
			return df.format(ratio);
		}
		return "NaN";
	}

//***************************************保护动作时间******************************
	/**
	 * 根据年、电压等级，获取保护动作时间
	 * @param startYear
	 * @param endYear
	 * @param voltage
	 * @return
	 */

	@GetMapping("/getProtectActTimeCount/{startYear}/{endYear}/{voltage}")
	public String getProtectActTimeCount(@PathVariable("startYear") String startYear,@PathVariable("endYear") String endYear,@PathVariable("voltage") String voltage) {
		List<ProtectActTimeCount> list = new ArrayList<ProtectActTimeCount>();
		Integer start = Integer.parseInt(startYear);
		Integer end = Integer.parseInt(endYear);
		Integer v = Integer.parseInt(voltage);
		List<Integer> voltages = new ArrayList<Integer>();
		if (v != 0) {
			voltages.add(v);
		} else if (v == 0) {
			voltages = comM.getVoltages();
		}
		if (start.equals(end)) {
			// 查询当年度1-12月份的数据
			// list = getMonthDate(start, voltages);
			list = getProtectActTimeByMothonfromOMS(start, voltages);
		} else {
			// 查询从startYear到endYear的年度数据
			for (int y = start; y <= end; y++) {
				// list.addAll(getYearData(y, voltages));
				list.addAll(getProtectActTimeByYearfromOms(y, voltages));
			}
		}
		JSONArray jsa = new JSONArray();
		for (ProtectActTimeCount count : list) {
			JSONArray jsArr = new JSONArray();
			jsArr.add(count.getYear());
			jsArr.add(count.getMonth());
			jsArr.add(count.getVoltage());
			jsArr.add(df.format(count.getActTimeAve()));
			jsa.add(jsArr);
		}
		return jsa.toString();
	}

	private List<ProtectActTimeCount> getProtectActTimeByYearfromOms(int year, List<Integer> voltages) {
		FaultContinuedTimeCountstrategy oms = manager.new OMSCountstrategy();
		List<ProtectActTimeCount> list = new ArrayList<ProtectActTimeCount>();
		List<ProtectActTimeCount> result = new ArrayList<ProtectActTimeCount>();
		for (Integer vol : voltages) {
			list = getProtectActTimeCount(oms.findActTimeCount(year, null, vol, null));
			Float avg = getSumAvgProtectActCount(list);
			ProtectActTimeCount count = new ProtectActTimeCount();
			count.setActTimeAve(avg);
			count.setYear(year);
			count.setVoltage(vol);
			result.add(count);
		}
		return result;
	}

	/**
	 * 查询当年1-12月份的数据
	 * @param year
	 * @param voltages
	 * @return
	 */
	private List<ProtectActTimeCount> getMonthDate(Integer year, List<Integer> voltages) {
		List<ProtectActTimeCount> list = new ArrayList<ProtectActTimeCount>();
		for (Integer vol : voltages) {
			List<ProtectActTimeCount> results = manager.findMonthProtectActTimeCount(year, null, vol, null);
			list.addAll(countProtectActListByMonth(results, year, vol));
		}
		return list;
	}

	/**
	 * 查询当年1-12月份的数据 
	 * @param start
	 * @param voltages
	 * @return  List<ProtectActTimeCount>
	 */
	private List<ProtectActTimeCount> getProtectActTimeByMothonfromOMS(Integer start, List<Integer> voltages) {
		FaultContinuedTimeCountstrategy oms = manager.new OMSCountstrategy();
		List<ProtectActTimeCount> list = new ArrayList<ProtectActTimeCount>();
		for (Integer vol : voltages) {
			List<ProtectActTimeCount> results = getProtectActTimeCount(oms.findActTimeCount(start, null, vol, null));
			list.addAll(countProtectActListByMonth(results, start, vol));
		}
		return list;
	}

	/**
	 * 根据集合获取map 根据map获得平均时间 
	 * @param findMonthProtectActTimeCount
	 * @return List<ProtectActTimeCount>
	 */
	private List<ProtectActTimeCount> getProtectActTimeCount(List<?> findMonthProtectActTimeCount) {
		List<ProtectActTimeCount> list = new ArrayList<ProtectActTimeCount>();
		Map<String, List<Object>> map = getMap(findMonthProtectActTimeCount);
		for (String key : map.keySet()) {
			List<Object> lt = map.get(key);
			if (null != lt) {
				double totalTime = 0;
				int num = 0;
				for (Object obj : lt) {
					Object[] objs = (Object[]) obj;
					if (null != objs[10]) {// faultTime
						double faultTime = (Double.valueOf(objs[10].toString()));
						totalTime += faultTime;
						num++;
					}
				}
				ProtectActTimeCount record = new ProtectActTimeCount();
				record.setId(ObjectId.get().toString());
				String[] d = ((String) key).split("-");
				record.setYear(Integer.parseInt(d[0]));
				record.setMonth(Integer.parseInt(d[1]));
				int voltage = (Integer.valueOf(d[3].toString().replace(".0", "")));
				record.setVoltage(voltage);
				record.setStatus(0);
				// record.setSubCompany("-");
				if (num != 0) {
					// 将微秒转为毫秒
					String faultTimeAve = df.format((float) totalTime / (num));
					record.setActTimeAve(Float.parseFloat(faultTimeAve));
				}
				list.add(record);
			}
		}
		return list;
	}

	/**
	 * 根据年、月、电压等级，计算保护动作时间之和
	 * @param list
	 * @param year
	 * @param voltage
	 * @return
	 */
	private List<ProtectActTimeCount> countProtectActListByMonth(List<ProtectActTimeCount> list, Integer year, Integer voltage) {
		Map<Integer, List<ProtectActTimeCount>> map = new HashMap<>(); // <月，List>
		for (ProtectActTimeCount count : list) {
			Integer month = count.getMonth();
			List<ProtectActTimeCount> lt = map.get(month);
			if (null == lt) {
				lt = new ArrayList<ProtectActTimeCount>();
				map.put(month, lt);
			}
			lt.add(count);
		}
		List<ProtectActTimeCount> results = new ArrayList<ProtectActTimeCount>();
		for (Integer month : map.keySet()) {
			List<ProtectActTimeCount> lt = map.get(month);
			Float sum = 0f;
			for (ProtectActTimeCount bean : lt) {
				if(bean.getActTimeAve()!=null) {
				 sum += bean.getActTimeAve();
				}
			}
			float avg = 0f;
			if (lt.size() > 0) {
				avg = sum / lt.size();
			}
			ProtectActTimeCount result = new ProtectActTimeCount();
			result.setYear(year);
			result.setMonth(month);
			result.setVoltage(voltage);
			result.setActTimeAve(avg);
			results.add(result);
		}
		return results;
	}

	/**
	 * 根据年、电压等级，获取年度数据
	 * @param year
	 * @param voltage
	 * @return
	 */
	private List<ProtectActTimeCount> getYearData(Integer year, List<Integer> voltages) {
		List<ProtectActTimeCount> result = new ArrayList<ProtectActTimeCount>();
		for (Integer vol : voltages) {
			// 首先查询全年的数据
			List<ProtectActTimeCount> list = manager.findYearProtectActTimeCount(year, vol, null);
			if (list.size() == 0) {
				// 全年数据不存在时，查询当年1-12月份的数据
				list = manager.findMonthProtectActTimeCount(year, null, vol, null);
			}
			Float avg = getSumAvgProtectActCount(list);
			ProtectActTimeCount count = new ProtectActTimeCount();
			count.setActTimeAve(avg);
			count.setYear(year);
			count.setVoltage(vol);
			result.add(count);
		}
		return result;
	}

	private Float getSumAvgProtectActCount(List<ProtectActTimeCount> list) {
		Float result = 0f;
		if (list.size() > 0) {
			Float sum = 0f;
			for (ProtectActTimeCount count : list) {
				if(count.getActTimeAve()!=null) {
					sum += count.getActTimeAve();
				}
			}
			result = sum / list.size();
		}
		return result;
	}

	/**
	 * 根据年、电压等级，获取保护动作时间
	 * @param startYear
	 * @param endYear
	 * @param voltage
	 * @return
	 */

	@GetMapping("/getProtectActTimeDetail/{startYear}/{endYear}/{voltage}")
	public String getProtectActTimeDetail(@PathVariable("startYear") String startYear,@PathVariable("endYear") String endYear,@PathVariable("voltage") String voltage) {
		List<Object> result = new ArrayList<Object>();
		Integer start = Integer.parseInt(startYear);
		Integer end = Integer.parseInt(endYear);
		Integer v = Integer.parseInt(voltage);
		List<Integer> voltages = new ArrayList<Integer>();
		if (v != 0) {
			voltages.add(v);
		} else if (v == 0) {
			voltages = comM.getVoltages();
		}
		for (int year = start; year <= end; year++) {
			for (Integer vol : voltages) {
				List<?> list = countM.getProtectActTimeDetail(year, null, vol);
				result.addAll(list);
			}
		}
		JSONArray jsa = new JSONArray();
		for (Object object : result) {
			Object[] obj = (Object[]) object;
			if (null != obj[3]) {
				JSONArray jsArr = new JSONArray();
				jsArr.add(obj[0]); // 年
				jsArr.add(obj[1]); // 月
				jsArr.add(obj[2]); // 电压
				Integer time = (Integer) obj[3]; // 保护动作时间，微秒，需要转化为毫秒
				if (null != time) {
					jsArr.add((float) time / 1000); // 保护动作时间，毫秒
				}
				jsa.add(jsArr);
			}
		}
		return jsa.toString();
	}

	/**
	 * 根据年、电压等级，获取保护动作时间
	 * @param startYear
	 * @param endYear
	 * @param voltage
	 * @return
	 */

	@GetMapping("/getProtectActTimeDetailfromOMS/{startYear}/{endYear}/{voltage}")
	public String getProtectActTimeDetailfromOMS(@PathVariable("startYear") String startYear,@PathVariable("endYear") String endYear,@PathVariable("voltage") String voltage) {
		FaultContinuedTimeCountstrategy oms = manager.new OMSCountstrategy();
		List<Object> result = new ArrayList<Object>();
		Integer start = Integer.parseInt(startYear);
		Integer end = Integer.parseInt(endYear);
		Integer v = Integer.parseInt(voltage);
//		List<Integer> voltages = new ArrayList<Integer>();
//		if (v != 0) {
//			voltages.add(v);
//		} else if (v == 0) {
//			voltages = comM.getVoltages();
//		}
//		for (int year = start; year <= end; year++) {
//			for (Integer vol : voltages) {
//				List<?> list = oms.findActTimeCount(year, null, vol, null);
//				result.addAll(list);
//			}
//		}
		for (int year = start; year <= end; year++) {
			List<?> list = oms.findActTimeCount(year, null, v, null);
			result.addAll(list);
	      }
		JSONArray jsa = new JSONArray();
		for (Object object : result) {
			Object[] obj = (Object[]) object;
			if (null != obj[10]) {
				JSONArray jsArr = new JSONArray();
				Date faultDate = (Date) obj[1];
				String date = DateUtil.getStringDate(faultDate, DateUtil.pattern_ymd000);
				int year = Integer.valueOf(date.split("-")[0]);
				int month = Integer.valueOf(date.split("-")[1]);
				jsArr.add(year); // 年
				jsArr.add(month); // 月
				jsArr.add(obj[3]); // 电压
				String time = obj[10].toString(); // 保护动作时间，微秒，需要转化为毫秒
				if (null != time) {
					float timeUs = Float.parseFloat(time);
					jsArr.add(timeUs); // 保护动作时间，毫秒
				}
				jsa.add(jsArr);
			}
		}
		return jsa.toString();
	}

	// ***************************************断路器动作时间******************************
	/**
	 * 根据年、电压等级，获取断路器动作时间
	 * @param startYear
	 * @param endYear
	 * @param voltage
	 * @return
	 */

	@GetMapping("/getBreakerActTimeCount/{startYear}/{endYear}/{voltage}")
	public String getBreakerActTimeCount(@PathVariable("startYear") String startYear,@PathVariable("endYear") String endYear,@PathVariable("voltage") String voltage) {
		List<BreakerActTimeCount> list = new ArrayList<BreakerActTimeCount>();
		Integer start = Integer.parseInt(startYear);
		Integer end = Integer.parseInt(endYear);
		Integer v = Integer.parseInt(voltage);
		List<Integer> voltages = new ArrayList<Integer>();
		if (v != 0) {
			voltages.add(v);
		} else if (v == 0) {
			voltages = comM.getVoltages();
		}
		if (start.equals(end)) {
			// 查询当年度1-12月份的数据
			// list = getBreakerMonthDate(start, voltages);
			list = getBreakerTimeByMonthAndVolfromOMS(start, voltages);
		} else {
			// 查询从startYear到endYear的年度数据
			for (int y = start; y <= end; y++) {
				// list.addAll(getBreakerYearData(y, voltages));
				list.addAll(getBreakerTimeByYearDataFromOMS(y, voltages));
			}
		}
		JSONArray jsa = new JSONArray();
		for (BreakerActTimeCount count : list) {
			JSONArray jsArr = new JSONArray();
			jsArr.add(count.getYear());
			jsArr.add(count.getMonth());
			jsArr.add(count.getVoltage());
			jsArr.add(df.format(count.getActionTimeInterval()));
			jsa.add(jsArr);
		}
		return jsa.toString();
	}

	private List<BreakerActTimeCount> getBreakerTimeByYearDataFromOMS(int year, List<Integer> voltages) {
		FaultContinuedTimeCountstrategy oms = manager.new OMSCountstrategy();
		List<BreakerActTimeCount> list = new ArrayList<BreakerActTimeCount>();
		List<BreakerActTimeCount> result = new ArrayList<BreakerActTimeCount>();
		for (Integer vol : voltages) {
			list = getBreakerTimeCount(oms.findActTimeCount(year, null, vol, null));
			Float avg = getSumAvgBreakerActCount(list);
			BreakerActTimeCount count = new BreakerActTimeCount();
			count.setActionTimeInterval(avg);
			count.setYear(year);
			count.setVoltage(vol);
			result.add(count);
		}
		return result;
	}

	private List<BreakerActTimeCount> getBreakerTimeByMonthAndVolfromOMS(Integer start, List<Integer> voltages) {
		FaultContinuedTimeCountstrategy oms = manager.new OMSCountstrategy();
		List<BreakerActTimeCount> list = new ArrayList<BreakerActTimeCount>();
		for (Integer vol : voltages) {
			List<BreakerActTimeCount> results = getBreakerTimeCount(oms.findActTimeCount(start, null, vol, null));
			list.addAll(countBreakerActListByMonth(results, start, vol));
		}

		return list;
	}

	/**
	 * 根据集合获取map 根据map获得平均时间 
	 * @param findMonthProtectActTimeCount
	 * @return  List<BreakerActTimeCount>
	 */
	private List<BreakerActTimeCount> getBreakerTimeCount(List<?> findMonthProtectActTimeCount) {
		List<BreakerActTimeCount> list = new ArrayList<BreakerActTimeCount>();
		Map<String, List<Object>> map = getMap(findMonthProtectActTimeCount);
		for (String key : map.keySet()) {
			List<Object> lt = map.get(key);
			if (null != lt) {
				double totalTime = 0;
				int num = 0;
				for (Object obj : lt) {
					Object[] objs = (Object[]) obj;
					if (null != objs[12]) {// faultTime
						double faultTime = (Double.valueOf(objs[12].toString()));
						totalTime += faultTime;
						num++;
					}
				}
				BreakerActTimeCount record = new BreakerActTimeCount();
				record.setId(ObjectId.get().toString());
				String[] d = ((String) key).split("-");
				record.setYear(Integer.parseInt(d[0]));
				record.setMonth(Integer.parseInt(d[1]));
				int voltage = (Integer.valueOf(d[3].toString().replace(".0", "")));
				record.setVoltage(voltage);
				record.setStatus(0);
				// record.setSubCompany("-");
				if (num != 0) {
					// 将微秒转为毫秒
					String faultTimeAve = df.format((float) totalTime / (num));
					record.setActionTimeInterval(Float.parseFloat(faultTimeAve));
				}
				list.add(record);
			}
		}
		return list;
	}

	/**
	 * 查询当年1-12月份的数据
	 * @param year
	 * @param voltages
	 * @return
	 */
	private List<BreakerActTimeCount> getBreakerMonthDate(Integer year, List<Integer> voltages) {
		List<BreakerActTimeCount> list = new ArrayList<BreakerActTimeCount>();
		for (Integer vol : voltages) {
			List<BreakerActTimeCount> results = manager.findMonthBreakerActTimeCount(year, null, vol, null);
			list.addAll(countBreakerActListByMonth(results, year, vol));
		}
		return list;
	}

	/**
	 * 根据年、月、电压等级，计算保护动作时间之和
	 * @param list
	 * @param year
	 * @param voltage
	 * @return
	 */
	private List<BreakerActTimeCount> countBreakerActListByMonth(List<BreakerActTimeCount> list, Integer year, Integer voltage) {
		Map<Integer, List<BreakerActTimeCount>> map = new HashMap<>(); // <月，List>
		for (BreakerActTimeCount count : list) {
			Integer month = count.getMonth();
			List<BreakerActTimeCount> lt = map.get(month);
			if (null == lt) {
				lt = new ArrayList<BreakerActTimeCount>();
				map.put(month, lt);
			}
			lt.add(count);
		}
		List<BreakerActTimeCount> results = new ArrayList<BreakerActTimeCount>();
		for (Integer month : map.keySet()) {
			List<BreakerActTimeCount> lt = map.get(month);
			Float sum = 0f;
			for (BreakerActTimeCount bean : lt) {
				if (null != bean.getActionTimeInterval()) {
					sum += bean.getActionTimeInterval();
				}
			}
			float avg = 0f;
			if (lt.size() > 0) {
				avg = sum / lt.size();
			}
			BreakerActTimeCount result = new BreakerActTimeCount();
			result.setYear(year);
			result.setMonth(month);
			result.setVoltage(voltage);
			result.setActionTimeInterval(avg);
			results.add(result);
		}
		return results;
	}

	/**
	 * 根据年、电压等级，获取年度数据
	 * @param year
	 * @param voltage
	 * @return
	 */
	private List<BreakerActTimeCount> getBreakerYearData(Integer year, List<Integer> voltages) {
		List<BreakerActTimeCount> result = new ArrayList<BreakerActTimeCount>();
		for (Integer vol : voltages) {
			// 首先查询全年的数据
			List<BreakerActTimeCount> list = manager.findYearBreakerActTimeCount(year, vol, null);
			if (list.size() == 0) {
				// 全年数据不存在时，查询当年1-12月份的数据
				list = manager.findMonthBreakerActTimeCount(year, null, vol, null);
			}
			Float avg = getSumAvgBreakerActCount(list);
			BreakerActTimeCount count = new BreakerActTimeCount();
			count.setActionTimeInterval(avg);
			count.setYear(year);
			count.setVoltage(vol);
			result.add(count);
		}
		return result;
	}

	private Float getSumAvgBreakerActCount(List<BreakerActTimeCount> list) {
		Float result = 0f;
		if (list.size() > 0) {
			Float sum = 0f;
			for (BreakerActTimeCount count : list) {
				if(null!=count.getActionTimeInterval()) {
					sum += count.getActionTimeInterval();
				}
			}
			result = sum / list.size();
		}
		return result;
	}

	/**
	 * 根据年、电压等级，获取保护动作时间
	 * @param startYear
	 * @param endYear
	 * @param voltage
	 * @return
	 */

	@GetMapping("/getBreakerActTimeDetail/{startYear}/{endYear}/{voltage}")
	public String getBreakerActTimeDetail(@PathVariable("startYear") String startYear,@PathVariable("endYear") String endYear,@PathVariable("voltage") String voltage) {
		List<Object> result = new ArrayList<Object>();
		Integer start = Integer.parseInt(startYear);
		Integer end = Integer.parseInt(endYear);
		Integer v = Integer.parseInt(voltage);
		List<Integer> voltages = new ArrayList<Integer>();
		if (v != 0) {
			voltages.add(v);
		} else if (v == 0) {
			voltages = comM.getVoltages();
		}
		for (int year = start; year <= end; year++) {
			for (Integer vol : voltages) {
				List<?> list = countM.getBreakerActTimeDetail(year, null, vol);
				result.addAll(list);
			}
		}
		JSONArray jsa = new JSONArray();
		for (Object object : result) {
			Object[] obj = (Object[]) object;
			if (null != obj[3]) {
				JSONArray jsArr = new JSONArray();
				jsArr.add(obj[0]); // 年
				jsArr.add(obj[1]); // 月
				jsArr.add(obj[2]); // 电压
				Integer time = (Integer) obj[3]; // 断路器动作时间，微秒，需要转化为毫秒
				if (null != time) {
					jsArr.add((float) time / 1000); // 断路器动作时间，毫秒
				}
				jsa.add(jsArr);
			}
		}
		return jsa.toString();
	}


	/**
	 * 根据年、电压等级，获取保护动作时间
	 * @param startYear
	 * @param endYear
	 * @param voltage
	 * @return
	 */

	@GetMapping("/getBreakerActTimeDetailFromOMS/{startYear}/{endYear}/{voltage}")
	public String getBreakerActTimeDetailFromOMS(@PathVariable("startYear") String startYear,@PathVariable("endYear") String endYear,@PathVariable("voltage") String voltage) {
		FaultContinuedTimeCountstrategy oms = manager.new OMSCountstrategy();
		List<Object> result = new ArrayList<Object>();
		Integer start = Integer.parseInt(startYear);
		Integer end = Integer.parseInt(endYear);
		Integer v = Integer.parseInt(voltage);
		for (int year = start; year <= end; year++) {
				List<?> list = oms.findActTimeCount(year, null, v, null);
				result.addAll(list);
		}
		JSONArray jsa = new JSONArray();
		for (Object object : result) {
			Object[] obj = (Object[]) object;
			if (null != obj[12]) {
				JSONArray jsArr = new JSONArray();
				Date faultDate = (Date) obj[1];
				String date = DateUtil.getStringDate(faultDate, DateUtil.pattern_ymd000);
				int year = Integer.valueOf(date.split("-")[0]);
				int month = Integer.valueOf(date.split("-")[1]);
				jsArr.add(year); // 年
				jsArr.add(month); // 月
				jsArr.add(obj[3]); // 电压
				String time = obj[12].toString(); // 断路器动作时间，微秒，需要转化为毫秒
				if (null != time) {
					float timeUs = Float.parseFloat(time);
					jsArr.add(timeUs); // 断路器动作时间，毫秒
				}
				jsa.add(jsArr);
			}
		}
		return jsa.toString();
	}

	/**
	 * 根据开始年/结束年/电压等级/故障持续时间范围 
	 * 1.得到startYear endYear voltage rangeStart rangeEnd
	 * 2.
	 */

	@GetMapping("/getDetails/{startYear}/{endYear}/{voltage}/{range1}/{range2}/{chartId}/{month}")
	public String getDetails(@PathVariable("startYear") String startYear,@PathVariable("endYear") String endYear,@PathVariable("voltage") String voltage,
			@PathVariable("range1") Integer range1,@PathVariable("range2") Integer range2,@PathVariable("chartId") String chartId,@PathVariable("month") String month) {
		String flag = "primaryProtectTime";
		if(chartId.equals("faultDetail")||chartId.equals("faultAvgCount")) { //故障系统持续时间
			flag = "faultContinueTime";
		}else if(chartId.equals("protectDetail")||chartId.equals("protectAvgCount")) {//主保护
			flag = "primaryProtectTime";
		}else if(chartId.equals("breakerDetail")||chartId.equals("breakerCount")) {//断路器
			flag = "breakerActionTime";
		}
		FaultContinuedTimeCountstrategy oms = manager.new OMSCountstrategy();
		  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Integer start = Integer.parseInt(startYear);
		Integer end = Integer.parseInt(endYear);
		Integer v = Integer.parseInt(voltage);
//		List<Integer> voltages = new ArrayList<Integer>();
		List<Object> result = new ArrayList<Object>();
//		if (v != 0) {
//			voltages.add(v);
//		} else if (v == 0) {
//			voltages = comM.getVoltages();
//		}
		for (int year = start; year <= end; year++) {
//			for (Integer vol : voltages) {
				List<?> list = oms.findActTimeCount(year,Integer.parseInt(month)==0?null:Integer.parseInt(month), v, null, range1, range2,flag);
				result.addAll(list);
//			}
		}
		JSONArray jsa = new JSONArray();
		for (Object object : result) {
			Object[] obj = (Object[]) object;
			if (null != obj[11]) {// 故障持续时间
				Date faultTime = (Date) obj[4];
				JSONArray jsArr = new JSONArray();
				jsArr.add(obj[5]); // 线路名称
				jsArr.add(formatter.format(faultTime)); // 时间
				jsArr.add(obj[2]); // 设备类型
				jsArr.add(obj[3]); // 电压
				jsArr.add(obj[6]); // 故障类型
				jsArr.add(obj[7]); // 故障相别
				jsArr.add(obj[8]); // 故障内容
				String lastingtime = "0";
				if(flag.equals("faultContinueTime")){ //故障系统持续时间
					lastingtime = obj[11].toString(); // 故障持续时间，微秒，需要转化为毫秒
				}else if(flag.equals("primaryProtectTime")) {//主保护
					lastingtime = obj[10].toString(); 
				}else if(flag.equals("breakerActionTime")) {//断路器
					lastingtime = obj[12].toString(); 
				}
				if (StringUtils.isNotEmpty(lastingtime)) {
					float timeUs = Float.parseFloat(lastingtime);
					jsArr.add(timeUs); // 故障持续时间，毫秒
				} else {
					jsArr.add(0); // 故障持续时间，毫秒
				}
				jsa.add(jsArr);
			}
		}
		return jsa.toString();
	}

	/**
	 * 根据年、电压等级，获取保护动作时间
	 * @param startYear
	 * @param endYear
	 * @param voltage
	 * @return
	 */

	@GetMapping("/getProtectActTimeDetailByStartYearAndEndYearAndRange/{startYear}/{endYear}/{voltage}")
	public String getProtectActTimeDetailFromOMSByStartYearAndEndYearAndRange(@PathVariable("startYear") String startYear,
			@PathVariable("endYear") String endYear,@PathVariable("voltage") String voltage) {
		FaultContinuedTimeCountstrategy oms = manager.new OMSCountstrategy();
		List<Object> result = new ArrayList<Object>();
		Integer start = Integer.parseInt(startYear);
		Integer end = Integer.parseInt(endYear);
		Integer v = Integer.parseInt(voltage);
//		List<Integer> voltages = new ArrayList<Integer>();
//		if (v != 0) {
//			voltages.add(v);
//		} else if (v == 0) {
//			voltages = comM.getVoltages();
//		}
//		for (int year = start; year <= end; year++) {
//			for (Integer vol : voltages) {
//				List<?> list = oms.findActTimeCount(year, null, vol, null);
//				result.addAll(list);
//			}
//		}
		for (int year = start; year <= end; year++) {
			List<?> list = oms.findActTimeCount(year, null, v, null);
			result.addAll(list);
	      }
		JSONArray jsa = new JSONArray();
		for (Object object : result) {
			Object[] obj = (Object[]) object;
			if (null != obj[10]) {
				JSONArray jsArr = new JSONArray();
				Date faultDate = (Date) obj[1];
				String date = DateUtil.getStringDate(faultDate, DateUtil.pattern_ymd000);
				int year = Integer.valueOf(date.split("-")[0]);
				int month = Integer.valueOf(date.split("-")[1]);
				jsArr.add(year); // 年
				jsArr.add(month); // 月
				jsArr.add(obj[3]); // 电压
				String time = obj[10].toString(); // 保护动作时间，微秒，需要转化为毫秒
				if (null != time) {
					float timeUs = Float.parseFloat(time);
					jsArr.add(timeUs); // 保护动作时间，毫秒
				}
				jsa.add(jsArr);
			}
		}
		return jsa.toString();
	}
	

}
